﻿using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.ListFilter;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Util;
using Kingdee.BOS.JSON;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Web.Core;
using Kingdee.BOS.Web.DynamicForm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Web.List;

namespace DevSamPle.FormPlugin
{
    [Description("【表单插件】创建列表视图，执行列表操作"), HotUpdate]
    public class ToListOperation : AbstractDynamicFormPlugIn
    {
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            if (e.BarItemKey.EqualsIgnoreCase("ToList"))
            {
                var formId = "PUR_PurchaseOrder";
                //过滤方案ID可通过SQL SELECT * FROM T_BAS_FILTERSCHEME where FFORMID='PUR_PurchaseOrder'查询
                var schemeld = "4a25487239504a7d8a7ef91eafcbec61";
                //创建列表视图
                var listView = CreateListView(this.Context, formId, schemeld);
                //列表取数
                listView.GetEntryData("FLIST", 0, 1000, null);
                /* 用于列表选中行的数据包，可通过http数据抓包获取其格式
                    [{
                    "FLIST": {
                    "fieldKey": "Selected",
                    "row": 3,
                    "selRows": "1,2,3",
                    "isClientNewRow": false,
                    "clientNewRows": ""
                    }
                    }]
                 */
                var row = 3;
                var selectedRows = new[] { 1, 2, 3 };
                var postDatas = new JSONArray();
                var jsObj = new JSONObject();
                postDatas.Add(jsObj);
                var jsObj2 = new JSONObject();
                jsObj.Put("FLIST", jsObj2);
                jsObj2["fieldKey"] = "Selected";
                jsObj2["row"] = 3;
                jsObj2["selRows"] = string.Join(",", selectedRows);
                jsObj2["isClientNewRow"] = false;
                jsObj2["clientNewRows"] = "";
                listView.LoadPostBackData(postDatas);
                listView.EntityRowClick("FLIST", row);
                listView.GetActions();
                // <3>执行列表操作
                var sub = listView.InvokeFormOperation("Submit");//提交
                if (sub)
                {
                    this.View.ShowMessage("执行列表提交操作成功！");
                }
                else
                {
                    this.View.ShowMessage("执行列表提交操作成功！");
                }
                //审核
                var aud = listView.InvokeFormOperation(FormOperationEnum.Audit);
                if (aud)
                {
                    this.View.ShowMessage("执行列表审核操作成功！");
                }
                else
                {
                    this.View.ShowMessage("执行列表审核操作不成功！");
                }
            }
        }

        private static ListView CreateListView(Context ctx, string formId, string schemeld = null)
        {
            // 元数据
            var formMetaData = FormMetaDataCache.GetCachedFormMetaData(ctx, formId);
            // ShowParameter
            var showParam = new ListShowParameter();
            showParam.FormId = formId;
            showParam.PageId = Guid.NewGuid().ToString();
            var paraObj = showParam.CreateWebParams();
            // OpenParameter
            var dynamicFormMetaDataService = new DynamicFormMetaDataService();
            var sessionManager = new SessionManager();
            dynamicFormMetaDataService.SetContext(sessionManager, ctx);
            dynamicFormMetaDataService.FormMetaData = formMetaData;
            dynamicFormMetaDataService.GetDynamicFormConfig(paraObj);
            var openParam = sessionManager.Get<DynamicFormOpenParameter>(showParam.PageId, FormConst.OPEN_PARAM);
            openParam.SetCustomParameter("SessionManager", sessionManager);
            // 创建视图
            var listView = new ListPrintWebService(schemeld, null, null);
            // 初始化视图
            var provider = GetListServiceProvider(openParam);
            listView.Initialize(openParam, provider);
            listView.LoadData();
            return listView;
        }

        private static IResourceServiceProvider GetListServiceProvider(DynamicFormOpenParameter param)
        {
            var provider = new FormServiceProvider();
            provider.Add(typeof(IDynamicFormView), CreateListView(param));
            provider.Add(typeof(DynamicFormViewPlugInProxy), new ListViewPlugInProxy());
            provider.Add(typeof(DynamicFormModelPlugInProxy), new ListModelPlugInProxy());
            provider.Add(typeof(IDynamicFormModelService), GetListModel(param));
            provider.Add(typeof(IListFilterModelService), GetListFilterModel());
            var type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DefaultValue.DefaultValueCalculator,Kingdee.BOS.Business.DynamicForm");
            provider.Add(typeof(IDefaultValueCalculator), Activator.CreateInstance(type));
            // 注册IDBModelService
            type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DBModel.DBModelService,Kingdee.BOS.Business.DynamicForm");
            provider.Add(typeof(IDBModelService), Activator.CreateInstance(type));
            return provider;
        }

        private static IListFilterModelService GetListFilterModel()
        {
            var type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.ListFilter.ListFilterModel,Kingdee.BOS.Model");
            return (IListFilterModelService)Activator.CreateInstance(type);
        }

        private static IDynamicFormModelService GetListModel(DynamicFormOpenParameter param)
        {
            var form = param.FormMetaData.BusinessInfo.GetForm();
            if (form.FormGroups != null && form.FormGroups.Count > 0)
            {
                var type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.List.TreeListModel,Kingdee.BOS.Model");
                return (IDynamicFormModelService)Activator.CreateInstance(type);
            }
            else
            {
                var type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.List.ListModel,Kingdee.BOS.Model");
                return (IDynamicFormModelService)Activator.CreateInstance(type);
            }
        }

        private static IDynamicFormView CreateListView(DynamicFormOpenParameter param)
        {
            var form = param.FormMetaData.BusinessInfo.GetForm();
            if (form.FormGroups != null && form.FormGroups.Count > 0)
            {
                return new TreeListView();
            }
            else
            {
                return new ListView();
            }
        }
    }
}
